"""
__author__ = 'berlinyoung'
@File   :base.py
@Date   :2022/5/18 21:59
-*- coding: utf-8 -*-
"""
import logging

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

class Base:
    logger = logging.getLogger()

    def __init__(self,driver:WebDriver = None):
        self.driver = driver

    def find(self,by,locator):

        self.logger.info("find")
        self.logger.info(by)
        self.logger.info(locator)
        return self.driver.find_element(by,locator)

    def finds(self,by,locator):

        self.logger.info("finds")
        self.logger.info(by)
        self.logger.info(locator)
        return self.driver.find_elements(by,locator)

    def find_click(self,by,locator):

        self.logger.info("find_click")
        self.find(by,locator).click()

    def find_send(self,by,locator,text):

        self.logger.info("find_send")
        self.find(by,locator).send_keys(text)

    def swipe_find(self,text,num=3):

        self.logger.info(f'swipe_find{text}')
        # 设置一个最大的查找次数
        for i in range(num):
            if i == num - 1:
                raise NoSuchElementException(f"找了{num-1}次，未找到")
            # 方法一，不要让find_element抛异常，在except中捕获异常，实现滑动操作
            try:
                element = self.find(MobileBy.XPATH,f"//*[@text='{text}']")
                return element
            except:
                self.logger.info("原屏未找到，进行滑动查找")
                # 如果未找到这个元素，捕获这个异常，并且 滑动 一屏
                # 滑动
                size = self.driver.get_window_size()
                # 'width','height'
                width = size.get('width')
                height = size.get('height')

                start_x = width / 2
                start_y = height * 0.8

                end_x = start_x
                end_y = height * 0.2

                duration = 2000

                self.driver.swipe(start_x,start_y,end_x,end_y,duration)

    def webdriver_wait(self,locate):
        WebDriverWait(self.driver,20)\
            .until(expected_conditions.element_to_be_clickable(locate))
